﻿using DongFangGuoKai.WCSPlatform.WebApi.Extensions;
using DongFangGuoKai.WCSPlatform.WebApi.ExternalSystem.AGVCommon;
using DongFangGuoKai.WCSPlatform.WebApi.Utils.UtilModel;
using DongFangGuoKai.WMSPlatform.Commn.ExtendModule;
using Microsoft.AspNetCore.Mvc;
using S7.Net;

namespace DongFangGuoKai.WCSPlatform.WebApi.Controllers
{
    /// <summary>
    /// 提供给AGV的接口
    /// </summary>
    [Route("api/[controller]/[action]"), ApiController, ApiExplorerSettings(GroupName = nameof(WCSApiVersions.V1))]
    public class SupplyAGVController : ControllerBase
    {
        private readonly AGVHttpClient aGVHttpTool;
        private readonly PlcDBAddress plcDBAddress;
        private readonly Plc plc;
        private readonly ILogger<SupplyAGVController> logger;
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="aGVHttpTool"></param>
        /// <param name="plcDBAddress"></param>
        /// <param name="plc"></param>
        /// <param name="logger"></param>
        public SupplyAGVController
        (
            AGVHttpClient aGVHttpTool,
            PlcDBAddress plcDBAddress,
            Plc plc,
            ILogger<SupplyAGVController> logger
        )
        {
            this.aGVHttpTool = aGVHttpTool;
            this.plcDBAddress = plcDBAddress;
            this.plc = plc;
            this.logger = logger;
        }
     
        /// <summary>
        /// AGV申请取放货： 已弃用 入库箱子到位后WMS会下发任务 直接取就好
        /// </summary>
        /// <returns></returns>
        [HttpPost, Obsolete]
        public ActionResult AgvExecute(AgvExecuteReq reqModel)
        {
            try
            {
                var model = new BoxApplyPassReq()
                {
                    ReqCode = reqModel.ReqCode,
                    TaskCode = reqModel.TaskCode,
                    Type = reqModel.Method == "applyIn" ? "1" : reqModel.Method == "applyOut" ? "2" : "0"
                };
                if(model.Type=="0")
                {
                    var failRes = new AGVBaseResModel("1", $"method的值为:{reqModel.Method}", reqModel.ReqCode);
                    logger.LogError($"AGV申请取放货;入参:[{reqModel.ToJson()}];出参:{failRes}");
                    return Ok(failRes);
                }
                var successRes = new AGVBaseResModel("0", "成功", reqModel.ReqCode);
                var boxApply = aGVHttpTool.BoxApplyPass(model,out var httpMsg);//回调agv
                logger.LogInformation($"AGV申请取放货;入参:[{reqModel.ToJson()}];出参:[{successRes.ToJson()}];{httpMsg}");
                return Ok();
            }
            catch (Exception ex)
            {
                logger.LogError($"AGV申请取放货;WCS故障:{ex.Message}");
                return Ok(new AGVBaseResModel("1", $"wcs故障:{ex.Message}", reqModel.ReqCode));
            }

        }
        /// <summary>
        /// AGV取放货 完成
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> AgvCallback(AgvCallbackReq reqModel)
        {
            try
            {
                var wiriteMsg = string.Empty;
                if (reqModel.Method == "outbin")
                {
                    //AGV取货完成
                    plc.Write(plcDBAddress.AgvPickComplete, true);
                    //并清空20的目标站和任务号
                    await plc.WriteIsAsync(plcDBAddress.InTerminalTarget, (ushort)0);
                    await plc.WriteIsAsync(plcDBAddress.InTerminalTask, (ushort)0);
                    ushort targetVal;
                    ushort taskVal;
                    do
                    {
                        targetVal = (ushort)plc.Read(plcDBAddress.InTerminalTarget);
                        taskVal = (ushort)plc.Read(plcDBAddress.InTerminalTask);
                        if (targetVal != 0 || taskVal != 0)
                        {
                            await plc.WriteAsync(plcDBAddress.InTerminalTarget, (ushort)0);
                            await plc.WriteAsync(plcDBAddress.InTerminalTask, (ushort)0);
                        }
                    } while (targetVal != 0 || taskVal != 0);
                    wiriteMsg = "A清空上层任务成功";
                }
                else if (reqModel.Method == "end")
                {
                    //AGV放料完成
                    plc.Write(plcDBAddress.AgvPlaceComplete, true);
                }
                else
                {
                    var failRes = new AGVBaseResModel("1", $"method的值为:{reqModel.Method}", reqModel.ReqCode);
                    logger.LogError($"AGV取放货完成;入参:[{reqModel.ToJson()}];出参:{failRes}");
                    return Ok(failRes);
                }

                var successRes = new AGVBaseResModel("0", "成功", reqModel.ReqCode);
                logger.LogInformation($"AGV取放货完成;入参:[{reqModel.ToJson()}];出参:[{successRes.ToJson()}];{wiriteMsg}");
                return Ok(successRes);
            }
            catch (Exception ex)
            {
                logger.LogError($"AGV取放完成,wcs故障:{ex.Message}");
                return Ok(new AGVBaseResModel("1", $"wcs故障:{ex.Message}", reqModel.ReqCode));
            }

        }

    }
}
